<?php
namespace app\api\logic;

use think\Model;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;

class Upload extends Model
{
    public function uploadHeadimg($base64_image_content, $user_id, $folder = '')
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];

            // 拼接文件路径和名字
            $new_file_name = date('Ymd') . uniqid() . mt_rand(0,9999) . '.' . $type;
            $save_dir = APP_ROOT_PATH . $folder;

            // 判断文件是否存在
            if(!file_exists($save_dir)) {
                mkdir($save_dir, 0777, true);
            }

            // dump($save_dir.$new_file_name);die;
            $new_file = $save_dir . $new_file_name;
            $info = file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
            if (!$info) {
                $base_return['success'] = false;
            } else {
                // oss上传
                $accessKeyId = config('ali_oss_accessKeyId');
                $accessKeySecret = config('ali_oss_accessKeySecret');
                $endpoint = config('ali_oss_endpoint');
                $bucket = config('ali_oss_bucket');
                $object = $new_file_name;
                $filePath = $new_file;
                try {
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    $ossClient->uploadFile($bucket, $object, $filePath);
                    $sql = "insert into aliyun_oss (name,tab,pid,add_time) values('" . $new_file_name .
                        "','user','" . $user_id . "','" . date('Y-m-d H:i:s') . "')";
                } catch (OssException $e) {
                    $sql = "insert into aliyun_oss (name,tab,pid,path,add_time) values('" . $new_file_name .
                        "','user','" . $user_id . "','" . $new_file . "','" . date('Y-m-d H:i:s') . "')";
                }
                Db::execute($sql);
                $ossId = Db::table('aliyun_oss')->getLastInsID();
                Db::table('user')->where('id', $user_id)->update(['head_img_id' => $ossId]);
                unlink($new_file);
                $base_return['success'] = true;
                $base_return['img_url'] = config('ali_cdn_url') . '/' . $new_file_name . '?' . config('ali_headimg_size');
            }
            return $base_return;
        }
    }
    





}